# 连接mysql数据库
import pymysql
import time


class MyMySQL:
    def __init__(self, host, user, password, database, port=3306, charset='utf8'):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.port = port
        self.charset = charset
        self.conn = None
        self.cursor = None

    def connect(self):
        self.conn = pymysql.connect(host=self.host, user=self.user, password=self.password, database=self.database,
                                    port=self.port, charset=self.charset)
        self.cursor = self.conn.cursor()

    def add(self, mydic):
        # 样例mydic={"标题":"xxxx","类型":"xx","领域":"xx","文章":"xx"}
        # 将样例加入到mysql中的表"文章库"中  表的表头为  标题 类型 领域 文章
        sql = "insert into 文章库(标题,类型,领域,文章) values('%s','%s','%s','%s')" % (
        mydic["标题"], mydic["类型"], mydic["领域"], mydic["文章"])
        # 如果数据库中已经有和mydic相同的标题 但是mydic中的类型或领域不为空且与数据库中不同则更新类型或领域
        if self.cursor.execute("select * from 文章库 where 标题='%s'" % mydic["标题"]) != 0:
            if mydic["类型"] != "" and self.cursor.execute(
                    "select * from 文章库 where 标题='%s' and 类型='%s'" % (mydic["标题"], mydic["类型"])) == 0:
                sql = "update 文章库 set 类型='%s'where 标题='%s'" % (
                    mydic["类型"], mydic["标题"]
                )
            elif mydic["领域"] != "" and self.cursor.execute(
                    "select * from 文章库 where 标题='%s' and 领域='%s'" % (mydic["标题"], mydic["领域"])) == 0:
                sql = "update 文章库 set 领域='%s'where 标题='%s'" % (
                    mydic["领域"], mydic["标题"]
                )

        try:
            self.cursor.execute(sql)
            self.conn.commit()
            print("添加成功")
            return True
        except Exception as e:
            print("添加失败", e)
            return False

    def is_connected(self):
        # 判断mysql是否连接口
        try:
            # 尝试执行ping操作
            self.conn.ping(reconnect=True)
            return True
        except Exception as e:
            return False
